﻿using System.Web.Http.Filters;
using System.Web.Http.Controllers;
using System.Web;
using System.Web.Security;
using System;
using System.Net.Http;
using WS.EKA.Utilities.EncryptTool;
using WS.EKA.Utilities.Consts;
using WS.EKA.Utilities.Extensions;
using Newtonsoft.Json;

namespace WS.EKA.Portal.Filters
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
    public class AuthencationFilter : ActionFilterAttribute
    {
        private bool isExclude { get; set; }
        public AuthencationFilter()
        {
        }
        public AuthencationFilter(bool isExclude)
        {
            this.isExclude = isExclude;
        }
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (isExclude)
            {
                base.OnActionExecuting(actionContext);
                return;
            }
            if (!HttpContext.Current.Request.IsAuthenticated)
            {
                 IllegalRequestOperation(actionContext);
                 return;
            }
            if (string.IsNullOrEmpty(HttpContext.Current.User.Identity.Name) ||
                !HttpContext.Current.User.Identity.IsAuthenticated)
            {
                IllegalRequestOperation(actionContext);
                return;
            }
            //var cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
            //if (cookie == null || string.IsNullOrEmpty(cookie.Value))
            //{
            //    IllegalRequestOperation(actionContext);
            //    return;
            //}
            //var ticket = FormsAuthentication.Decrypt(cookie.Value);
            //if (ticket == null || string.IsNullOrEmpty(ticket.UserData))
            //{
            //    IllegalRequestOperation(actionContext);
            //    return;
            //}
            //string encrptUserName = ticket.Name;
            //dynamic user =JsonConvert.DeserializeObject(ticket.UserData);
            //var encryptor = EncryptFactory.Create();
            //string verifyHash = user.UserName + UserConsts.WSMobile.ConfigValue();
            //if (!encryptor.VerifyMd5Hash(verifyHash, encrptUserName))
            //{
            //    IllegalRequestOperation(actionContext);
            //    return;
            //}

            //role validate here  user.Roles

            base.OnActionExecuting(actionContext);
        }

        private void IllegalRequestOperation(HttpActionContext actionContext)
        {
            actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
            {
                Content = new StringContent("Illegal request")
            };
        }
    }
}